package com.vf.s.mvc.city.service;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.vf.core.model.ZtreeNode;
import com.vf.s.common.model.city.BizCityMenu;

public class BizCityMenuService {

	protected final Log LOG = Log.getLog(getClass());


	
	public List<BizCityMenu> getChildrenAllTree(String pId) {
		List<BizCityMenu> list = getChildrenByPid(pId);
		for (BizCityMenu o : list) {
			o.setChildren(getChildrenAllTree(o.getId()));
		}
		return list;
	}

	/***
	 * 根据id 查询孩子
	 * 
	 * @param id
	 * @return
	 */
	public List<BizCityMenu> getChildrenByPid(String id) {
		String sql = "SELECT * FROM "+BizCityMenu.TABLE_NAME+" M WHERE M.PARENTID='" + id + "' ";
		sql = sql + " ORDER BY M.SORT";
		return BizCityMenu.dao.find(sql);
	}

	/***
	 * 菜单转成ZTreeNode
	 * @param olist 数据 open 是否展开所有 ifOnlyLeaf 是否只选叶子
	 * @return
	 */
	public List<ZtreeNode> toZTreeNode(List<BizCityMenu> olist, Boolean open, Boolean ifOnlyLeaf) {
		List<ZtreeNode> list = new ArrayList<ZtreeNode>();
		for (BizCityMenu o : olist) {
			ZtreeNode node = toZTreeNode(o);
			if (o.getChildren() != null && o.getChildren().size() > 0) {// 如果有孩子
				node.setChildren(toZTreeNode(o.getChildren(), open, ifOnlyLeaf));
				if (ifOnlyLeaf) {// 如果只选叶子
					node.setNocheck(true);
				}
				node.setIsParent(true);
			}
			node.setOpen(open);
			list.add(node);
		}
		return list;
	}

	public ZtreeNode toZTreeNode(BizCityMenu org) {
		ZtreeNode node = new ZtreeNode();
		node.setId(org.getId());
		
		node.setType(org.getType());
		node.setParentId(org.getParentId());
		if(StrKit.equals("Layers", org.getType()) || StrKit.equals("Maps", org.getType()) || StrKit.equals("Scenes", org.getType())) {
			node.setName(String.format("%s(%d)", org.getName(),org.getChildren().size()));
		}
		else {
			node.setName(org.getName());
		}
		return node;
	}

	public List<BizCityMenu> getAuthChildrenAllTree(String pId, String cityId) {
		List<BizCityMenu> list = getChildrenByPidAndRoleId(pId, cityId);
		for (BizCityMenu o : list) {
			o.setChildren(getAuthChildrenAllTree(o.getId(), cityId));
		}
		return list;
	}

	/***
	 * 根据id 查询孩子
	 * 
	 * @param id
	 * @return
	 */
	public List<BizCityMenu> getChildrenByPidAndRoleId(String id, String roleId) {
		return BizCityMenu.dao.find("select t.id,t.parentId as pId, t.name, "
				+ " (CASE  WHEN (SELECT count(id) as count from sys_role_permissions where menuId=t.id and roleId=? )>0 THEN true ELSE  false END ) as checked   "
				+ " from sys_menu  t  ORDER BY t.sort asc", roleId);
	}

}
